package cn.wolfcode.web.shiro;

import cn.wolfcode.web.domain.Employee;
import cn.wolfcode.web.mapper.EmployeeMapper;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

@Component("crmRealm")//创建CRMReaml对象
public class CRMReaml extends AuthorizingRealm {
    @Autowired
    private EmployeeMapper employeeMapper;

    //获取认证信息
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        String username = (String) token.getPrincipal();//获取存在令牌的数据(用户名)
        Employee employee = employeeMapper.selectByName(username);
        if (employee == null) {
            return null;
        }
//   SimpleAuthenticationInfo继承了 AuthenticationInfo
        return new SimpleAuthenticationInfo(employee, employee.getPassword(), this.getName());

        /*//       模拟数据库的真实账号和密码
        String username="zhangsan";
        String password="555";
//        如果账号正确,返回一个AuthenticationInfo对象
//    token 是装密码和账号信息的身份凭证
        if(username.equals(token.getPrincipal())){
            return  new SimpleAuthenticationInfo(username,
                    password,
                    this .getName());//数据源:当前 Realm 的名称
        }*/

//        有了这一步，Shiro就会通过自定义的 Realm进行账号校验了   到此，Shiro的认证功能已经成功的继承到了 CRM项目中。
//        目前可以很方便的完成登录验证，登录拦截，注销等功能。
    }

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        SimpleAuthenticationInfo info = new SimpleAuthenticationInfo();
        List<String>roles=new ArrayList<>();
        roles.add("role1");
        roles.add("role2");
        List<String> permissions=new ArrayList<>();
        permissions.add("user:list");
        permissions.add("user:delete");
        permissions.add("user:update");
        info.addRoles(roles);
        info.addStringPermissions(permissions);
        return info;
    }
}
